<template>
  <div class='setmeal'>
    <el-page-header @back="backSetmeal" :content="title">
    </el-page-header>
    <el-form ref="form" :model="SetmealBasic" :rules="SetmealRules" label-width="100px" label-position="left" style="margin: 56px 80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="套餐名称:" prop="setmealName">
            <el-input v-model="SetmealBasic.setmealName" style="width: 280px;" placeholder="请输入套餐名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="套餐分类:" prop="categoryId">
            <el-select v-model="SetmealBasic.categoryId" placeholder="请选择套餐分类" style="width: 280px;">
              <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="售价:" prop="price">
        <el-input v-model="SetmealBasic.price" style="width: 280px;" placeholder="请输入售价"></el-input>
      </el-form-item>
      <el-form-item label="排序:">
        <el-input v-model="SetmealBasic.sort" style="width: 280px;" placeholder="请输入排序"></el-input>
      </el-form-item>
      <el-form-item label="菜品配置:">
        <el-button type="warning" class="el-icon-plus" v-if="setmealDishList.length === 0"
          @click="addDish">添加菜品</el-button>
        <div class="dishTable" v-if="setmealDishList.length !== 0">
          <div class="dishList">
            <el-table ref="dishTable" :data="setmealDishList" border stripe>
              <el-table-column type="index" align="center">
              </el-table-column>
              <el-table-column prop="dishName" label="菜品名称" align="center">
              </el-table-column>
              <el-table-column prop="price" label="售价" align="center">
              </el-table-column>
              <el-table-column label="份量" align="center" width="200">
                <template slot-scope="scope">
                  <el-input-number size="small" v-model="scope.row.dishNum" :min="1"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="delSetmealDish(scope.row)" size="small" style="color: red">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="addBut">
            <el-button type="warning" @click="addDish">添加菜品</el-button>
          </div>
        </div>
      </el-form-item>
      <!-- 添加菜品弹窗-->
      <el-dialog title="添加菜品" :visible.sync="dishDishListVisible" :before-close="handelAddDishList">
        <div class="content">
          <div class="leftSelect">
            <el-cascader-panel :options="DishListByCategory" :props="propsCategory"
              @change="changeDishList"></el-cascader-panel>
            <el-cascader-panel :options="DishList" :props="propsDish" @change="Dishchecked" v-model="cascaderValue"></el-cascader-panel>
          </div>
          <div class="rightChecked">
            <div class="title">已选菜品（{{ selectDishList.length }}）</div>
            <div class="tags">
              <el-tag v-for="(tag,index) in selectDishList" :key="index" closable style="margin: 2px;" @close="removeDish(tag)"
                :disable-transitions="true">
                {{ tag.dishName }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-dialog>
      <el-form-item label="套餐图片:">
        <el-upload action list-type="picture-card" :http-request="uploadFile" :limit="3" :file-list="fileList"
          :on-remove="handleRemove" :on-exceed="limitFile">
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="套餐描述:">
        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="SetmealBasic.description"
          style="width: 803px;">
        </el-input>
      </el-form-item>
      <div style="margin-top: 35px"></div>
      <el-form-item>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="primary" @click="addOrEditSetmeal">保存</el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetForm">重置</el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="backSetmeal">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'

export default {
  name: '',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      baseSetmeal: '/setmeal-basic',
      title: '添加套餐',
      flag: true,
      id: 0,
      // 套餐输入对象
      SetmealBasic: {
        id: 0,
        setmealName: '',
        categoryId: '',
        price: 0,
        image: '',
        status: 0,
        description: '',
        setmealDishes: [],
        sort: 0,
        createUser: 0,
        // createDate: new Date(),
        updateUser: 0,
        // updateDate: new Date(),
        isDeleted: false
      },
      // 套餐输出对象
      SetmealBasicDto: {
        id: 0,
        setmealName: '',
        categoryId: '',
        price: 0,
        image: '',
        status: 0,
        description: '',
        dishAndNumDtos: [],
        sort: 0,
        createUser: '',
        createDate: new Date(),
        updateUser: '',
        updateDate: new Date(),
        isDeleted: false
      },
      categoryList: [],
      fileList: [],
      dishDishListVisible: false,
      cascaderValue: '',
      DishListByCategory: [],
      propsCategory: {
        value: 'id',
        label: 'categoryName'
      },
      DishList: [],
      propsDish: {
        multiple: true,
        value: 'id',
        label: 'dishName'
      },
      selectDishList: [],
      setmealDishList: [],
      SetmealRules: {
        setmealName: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择套餐分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入套餐价格', trigger: 'blur' }
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
  },
  // 方法集合
  methods: {
    async searchCategoryListByType () {
      await request({
        url: '/category-basic/category-list/1/1000',
        method: 'get',
        params: {
          type: 2
        }
      }).then(result => {
        this.categoryList = result.data.data.data
      })
    },
    // 回显套餐信息
    async backSetmealById () {
      if (this.flag) {
        // 添加套餐，不需要回显数据
        // 显示当前标题为添加套餐
        this.title = '添加套餐'
      } else {
        this.fileList = []
        // 编辑套餐，需要回显数据
        // 显示当前标题为编辑套餐
        this.title = '编辑套餐'
        // 回显数据
        await request({
          url: this.baseSetmeal + `/setmeal-basic/${this.id}`,
          method: 'get'
        }).then(result => {
          if (result.data.data != null) {
            this.SetmealBasicDto = result.data.data
            const { id, setmealName, categoryId, price, image, status, description, sort } = this.SetmealBasicDto
            this.SetmealBasic = { id, setmealName, categoryId, price, image, status, description, sort }
            if (this.SetmealBasic.image !== '') {
              const urlList = this.SetmealBasic.image.split(',')
              urlList.forEach(item => {
                const image = {
                  url: ''
                }
                image.url = item
                this.fileList.push(image)
              })
            }
            if (this.SetmealBasicDto.dishAndNumDtos.length !== 0) {
              this.SetmealBasicDto.dishAndNumDtos.forEach(item => {
                const setmealDish = {
                  dishId: 0,
                  dishName: '',
                  price: 0.0,
                  dishNum: 1
                }
                setmealDish.dishId = item.id
                setmealDish.dishName = item.dishName
                setmealDish.price = item.price
                setmealDish.dishNum = item.dishNum
                this.setmealDishList.push(setmealDish)
              })
            }
          } else {
            this.$message({
              message: '回显失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '回显失败',
            type: 'error'
          })
        })
      }
    },
    // 添加或修改套餐
    async addOrEditSetmeal () {
      const urlList = []
      this.fileList.forEach(item => {
        urlList.push(item.url)
      })
      this.SetmealBasic.image = urlList.join(',')
      this.SetmealBasic.image.substring(1)
      const tempList = []
      this.setmealDishList.forEach(item => {
        const setmealDish = {
          dishId: 0,
          dishNum: 0
        }
        setmealDish.dishId = item.dishId
        setmealDish.dishNum = item.dishNum
        tempList.push(setmealDish)
      })
      this.SetmealBasic.setmealDishes = tempList
      if (this.flag) {
        // 添加菜品
        await request({
          url: this.baseSetmeal + '/setmeal-basic',
          method: 'post',
          data: this.SetmealBasic
        }).then(result => {
          if (result.data.data) {
            this.backSetmeal('添加成功')
          } else {
            this.$message({
              message: '添加失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        })
      } else {
        // 修改菜品
        await request({
          url: this.baseSetmeal + '/setmeal-basic',
          method: 'put',
          data: this.SetmealBasic
        }).then(res => {
          if (res.data.data) {
            this.backSetmeal('修改成功')
          } else {
            this.$message({
              message: '修改失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '修改失败',
            type: 'error'
          })
        })
      }
    },
    // 返回套餐界面返回信息
    backSetmeal (msg) {
      this.$router.push({
        path: '/setmeal',
        query: {
          msg
        }
      })
    },
    // 重置表单数据
    resetForm () {
      this.SetmealBasic = {
        id: 0,
        setmealName: '',
        categoryId: '',
        price: 0,
        image: '',
        status: 0,
        description: '',
        setmealDishes: [],
        sort: 0,
        createUser: 0,
        createDate: new Date(),
        updateUser: 0,
        updateDate: new Date(),
        isDeleted: false
      }
    },
    /**
     * 文件上传
     */
    async uploadFile (file) {
      const fileData = new FormData()
      fileData.append('file', file.file)
      await request.post(
        '/file/upload-file',
        fileData,
        {
          'Content-Type': 'multipart/form-data;charset=utf-8'
        }
      ).then(res => {
        if (res.data.data != null) {
          const imageUrl = {
            url: ''
          }
          imageUrl.url = res.data.data
          this.fileList.push(imageUrl)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleRemove (file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    async addDish () {
      this.dishDishListVisible = true
      await request({
        url: '/dish-basic/category-dish-list',
        method: 'get'
      }).then(res => {
        if (res.data.data != null) {
          this.DishListByCategory = res.data.data
        }
      })
    },
    changeDishList (node) {
      this.DishListByCategory.forEach(item => {
        if (item.id === node[0]) {
          this.DishList = item.dishList
        }
      })
    },
    // 记录选择的菜品
    Dishchecked (node) {
      node.forEach(item => {
        this.DishList.forEach(dish => {
          if (item[0] === dish.id) {
            this.selectDishList.push(dish)
          }
        })
      })
      this.selectDishList = [...new Set(this.selectDishList)]
      // this.setmealDishList.forEach(setmealDish => {
      //   this.selectDishList.forEach(item => {
      //     if (setmealDish.dishName === item.dishName) {
      //       this.$message.error('该菜品已在菜品列表中存在，修改份量即可')
      //     }
      //   })
      // })
    },
    // 移除菜品标签
    removeDish (tag) {
      this.selectDishList.splice(this.selectDishList.indexOf(tag), 1)
    },
    // 关闭添加菜品弹窗
    handelAddDishList () {
      this.dishDishListVisible = false
      this.selectDishList.forEach(item => {
        const setmealDish = {
          dishId: 0,
          dishName: '',
          price: 0.0,
          dishNum: 1
        }
        setmealDish.dishId = item.id
        setmealDish.dishName = item.dishName
        setmealDish.price = item.price
        this.setmealDishList.push(setmealDish)
      })
      // let dishNames = []
      // tempList.forEach(item => {
      //   dishNames.push(item.dishName)
      // })
      // dishNames = [...new Set(dishNames)]
      // for (let i = 0; i < this.setmealDishList.length; i++) {
      //   if (dishNames.indexOf(this.setmealDishList[i].dishName) !== 0) {
      //     this.setmealDishList[i].num += 1
      //     dishNames.splice(dishNames.indexOf(this.setmealDishList[i].dishName), 1)
      //   }
      // }
      // this.setmealDishList = this.setmealDishList.forEach(item => {
      //   dishNames.forEach(dish => {
      //     if (item.dishName === dish) item.num += 1
      //   })
      // })
      // const mapBydishName = new Map()
      // dishNames.forEach(item => {
      //   const setmeales = []
      //   this.setmealDishList.forEach(setmeal => {
      //     if (item === setmeal.dishName) {
      //       setmeales.push(setmeal)
      //     }
      //   })
      //   mapBydishName.set(item, setmeales.length)
      // })
      // const xxx = []
      // mapBydishName.forEach((value, key) => {
      //   this.setmealDishList.forEach(setmeal => {
      //     if (setmeal.dishName === key) {
      //       setmeal.num = value
      //     }
      //     xxx.push(setmeal)
      //   })
      // })
      // const yyy = new Map()
      // dishNames.forEach(item => {
      //   const setmeales = []
      //   xxx.forEach(setmeal => {
      //     if (item === setmeal.dishName) {
      //       setmeales.push(setmeal)
      //     }
      //   })
      //   yyy.set(item, setmeales)
      // })
      // const zzz = []
      // yyy.forEach((value, key) => {
      //   dishNames.forEach(item => {
      //     if (value[0].dishName === item) {
      //       zzz.push(value[0])
      //     }
      //   })
      // })
      // this.setmealDishList = zzz
      // 关闭添加菜品弹窗后清空默认数据
      this.cascaderValue = ''
      // 关闭添加菜品弹窗后清空选中的菜品
      this.selectDishList = []
    },
    // 删除菜品套餐关联
    delSetmealDish (row) {
      console.log(row)
      this.setmealDishList.splice(this.setmealDishList.indexOf(row), 1)
    },
    limitFile () {
      this.$message({
        message: '当前只允许上传三张图片',
        type: 'error'
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.flag = this.$route.params.flag
    this.id = this.$route.params.id
    this.searchCategoryListByType()
    this.backSetmealById()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
  .setmeal {
      background-color: #fff;
      /* height: 810px; */
      padding: 20px 20px;
      border-radius: 30px;
    }
  .dishTable {
    width: 600px;
    padding: 5px;

    .addBut {
      margin-top: 5px;
    }
  }

  .content {
    display: flex;

    .leftSelect {
      display: flex;
    }

    .rightChecked {
      width: 300px;
      height: 191px;
      border: 1px solid #E4E7ED;
      border-radius: 5px;
      padding: 5px;

      .tags {
        width: 280px;
        height: 166px;
        overflow: scroll;
      }
    }
  }
</style>
